import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:landlore/customWidget/recordBodyCheckIn.dart';
import 'package:landlore/customWidget/recordBodyCheckOut.dart';
import 'package:landlore/dbUtil/databaseHelper.dart';
import 'package:landlore/screens/roomEditScreen.dart';
import 'package:path_provider/path_provider.dart';
import 'package:screenshot/screenshot.dart';
import 'package:share_plus/share_plus.dart';

import '../customWidget/recordBody.dart';
import '../model/orderVO.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

// import 'package:gallery_saver/gallery_saver.dart';
import 'dart:io';

import '../model/roomCheckInOut.dart';
import '../model/roomInfo.dart';

/***
 * 入住/退房 登记出单页面
 */
class OutputBillCheckInOutScreen extends StatefulWidget {
  final RoomCheckInOut roomCheckInOutVO;
  final RoomInfo roomInfo;

  OutputBillCheckInOutScreen({
    super.key,
    required this.roomCheckInOutVO,
    required this.roomInfo,
  });

  @override
  State<OutputBillCheckInOutScreen> createState() =>
      _OutputBillCheckInOutScreenState();
}

class _OutputBillCheckInOutScreenState
    extends State<OutputBillCheckInOutScreen> {
  RoomCheckInOut? roomCheckInOutVO;
  RoomInfo? roomInfo;
  final ScreenshotController screenshotController = ScreenshotController();

  File? file = null;

  @override
  initState() {
    roomCheckInOutVO = widget.roomCheckInOutVO;
    roomInfo = widget.roomInfo;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MediaQuery(
      ///设置文字大小不随系统设置改变
      data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: const Color(0xffe9c46a),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 35.sp,
              color: Colors.black,
            ),
            onPressed: () => Navigator.pop(context),
          ),
          title: Text(
            "出单",
            style: TextStyle(
                decoration: TextDecoration.none,
                fontSize: 30.sp,
                color: Colors.black,
                fontWeight: FontWeight.w900),
          ),
          centerTitle: true,
        ),
        body: Container(
            color: Colors.grey,
            child: ListView(
              children: roomCheckInOutVO == null
                  ? []
                  : [
                      Screenshot(
                          controller: screenshotController,
                          child: roomInfo!.state == 1?RecordBodyCheckIn(
                            orderVO: roomCheckInOutVO!,
                            callback: (result) {
                              setState(() {
                                roomCheckInOutVO = result;
                              });
                            },
                          )
                      :
                          RecordBodyCheckOut(
                            orderVO: roomCheckInOutVO!,
                            callback: (result) {
                              setState(() {
                                roomCheckInOutVO = result;
                              });
                            },
                          )
                      ),
                      Container(
                        padding: EdgeInsets.only(left: 100.w, right: 100.w),
                        margin: EdgeInsets.only(top: 40.h, bottom: 0.h),
                        height: 60.h,
                        child: ElevatedButton(
                            onPressed: () {
                              DatabaseHelper dbHelper = DatabaseHelper.instance;

                              //DB保存 房屋数据,若为退租,则只切换状态
                              if(roomInfo!.state == 1){
                                if (roomInfo?.id == null) {
                                  dbHelper.insertData(
                                      roomInfo!.toMap(), TableName.ROOM_INFO);
                                } else {
                                  dbHelper.updateData(
                                      roomInfo!.toMap(), TableName.ROOM_INFO,
                                      primaryKey: 'id',
                                      primaryKeyValue: roomInfo!.id!);
                                }
                              }else {
                                dbHelper.switchRoomState(roomInfo!.id!, false);
                              }

                               //DB保存 入住登记信息
                              dbHelper.insertData(roomCheckInOutVO!.toMap(),
                                  TableName.ROOM_CHECK_IN_OUT);

                              showDialog(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return AlertDialog(
                                      content: Text(
                                        '出单成功',
                                        style: TextStyle(fontSize: 30.sp),
                                      ),
                                      actions: [
                                        TextButton(
                                            onPressed: () async {
                                              //生成图片
                                              await createImg();

                                              try {
                                                await ImageGallerySaver.saveImage(
                                                    await file!.readAsBytes(),
                                                    name:
                                                    '${roomInfo?.roomNum}登记账单_${roomCheckInOutVO?.createDate?.year}_${roomCheckInOutVO?.createDate?.month}');
                                                print("Image saved to gallery");

                                                showSnackBar(context);
                                              } catch (e) {
                                                print(
                                                    "Failed to save image: $e");
                                              }
                                            },
                                            child: Text(
                                              '保存账单',
                                              style: TextStyle(fontSize: 25.sp),
                                            )),
                                        TextButton(
                                            onPressed: () async {
                                              //生成图片
                                              await createImg();

                                              Share.shareFiles([file!.path],
                                                  subject:
                                                  '${roomInfo?.roomNum}登记账单_${roomCheckInOutVO?.createDate?.year}_${roomCheckInOutVO?.createDate?.month}',
                                                  text:
                                                  '${roomInfo?.roomNum}登记账单_${roomCheckInOutVO?.createDate?.year}_${roomCheckInOutVO?.createDate?.month}');
                                            },
                                            child: Text(
                                              '分享账单',
                                              style: TextStyle(fontSize: 25.sp),
                                            )),
                                        TextButton(
                                            onPressed: () {
                                              Navigator.pop(context);
                                              Navigator.pop(context);
                                              Navigator.pop(context);
                                              Navigator.pop(context);
                                            },
                                            child: Text(
                                              '完成',
                                              style: TextStyle(fontSize: 25.sp),
                                            )),
                                      ],
                                    );
                                  });
                            },
                            style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(
                                    const Color(0xfff07167))),
                            child: Text(
                              '确认保存',
                              style: TextStyle(
                                  fontSize: 35.sp, fontWeight: FontWeight.w600),
                            )),
                      ),
                      Container(
                        padding: EdgeInsets.only(left: 150.w, right: 150.w),
                        margin: EdgeInsets.only(top: 25.h, bottom: 100.h),
                        height: 45.h,
                        child: ElevatedButton(
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            style: ButtonStyle(
                                backgroundColor: MaterialStateProperty.all(
                                    const Color(0xff264653))),
                            child: Text(
                              '修  改',
                              style: TextStyle(
                                  fontSize: 25.sp,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.white70),
                            )),
                      ),
                    ],
            )),
      ),
    );
  }

  void showSnackBar(BuildContext context) {
    const snackBar = SnackBar(
      content: Text('已保存到系统相册'),
      duration: Duration(seconds: 2), // Snackbar 显示的持续时间
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
  }

  createImg() async {
    //loading加载中动画
    showDialog(
      context: context,
      barrierDismissible: false,
      // Prevent dismissing the dialog by tapping outside
      builder: (BuildContext context) {
        return AlertDialog(
          content: Row(
            children: [
              const CircularProgressIndicator(),
              SizedBox(width: 16.w),
              const Text('处理中...'),
            ],
          ),
        );
      },
    );

    if (file == null) {
      // 创建一个临时文件
      final tempDirectory = (await getTemporaryDirectory()).path;
      file = File('$tempDirectory/bill.png');
      Uint8List? image = await screenshotController.capture(pixelRatio: 3);
      // 将截图数据写入临时文
      final imageFile = await file!.create();
      await imageFile.writeAsBytes(image!, flush: true);
    }
    Navigator.of(context).pop();
  }
}
